package com.cssl.controller;

import cn.hutool.core.util.ObjectUtil;
import com.cssl.domain.DtsAd;
import com.cssl.domain.DtsAdmin;
import com.cssl.domain.DtsRole;
import com.cssl.domain.dto.DtsAdDto;
import com.cssl.domain.dto.DtsAdminDto;
import com.cssl.domain.vo.LoginVO;
import com.cssl.service.DtsAdService;
import com.cssl.service.DtsAdminService;
import com.cssl.service.DtsRoleService;
import com.cssl.service.DtsUserService;
import com.cssl.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/admin")
@Api("管理员接口")
public class AdminController {
    @Autowired
    private DtsAdminService dtsAdminService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DtsRoleService service;


    /**
     * 登录
     *
     * @param loginVO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "管理员登录接口")
    Result login(@RequestBody LoginVO loginVO){
        System.out.println("登录:"+loginVO);
        return dtsAdminService.login(loginVO.getUsername(),loginVO.getPassword(),loginVO.getCode());
    }


    /**
     * 图形验证码
     *
     * @return
     */
    @GetMapping("/getCaptcha")
    @ApiOperation(value = "图形验证码", notes = "管理员登录图形验证码")
    Result getImageCode(){
        String key = getImageCodeKey(request);
        return dtsAdminService.getCode(key);
    }

    public String getImageCodeKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userInfo = request.getHeader("User-Agent");
        String md5 = MD5Util.string2MD5(ip + userInfo);
        return StorageVariable.LOGIN_CODE + md5;
    }

    @PostMapping("/getRole")
    public Result getRolesById(@RequestBody Map map) {
        DtsAdmin allInfoById = dtsAdminService.getAllInfoById(Integer.parseInt(map.get("id").toString()));
        String roleIds = allInfoById.getRoleIds();

        //正则表达式匹配数字
        Pattern pattern = Pattern.compile("\\[(\\d+)\\]");
        Matcher matcher = pattern.matcher(roleIds);
        List<Integer> rId = new ArrayList<>();
        while (matcher.find()) {
            String matchedNumber = matcher.group(1);
            rId.add(Integer.parseInt(matchedNumber));
        }
        List<DtsRole> roleById = service.getRoleById(rId, Integer.parseInt(map.get("id").toString()));
        System.out.println("roleById = " + roleById);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, roleById, System.currentTimeMillis());
    }

    //管理员列表
    @PostMapping("/listAdmin")
    public Result listAdmin(@RequestBody DtsAdminDto dto) {
        Map adminList = dtsAdminService.getDtsAdminList(dto);
        if (ObjectUtil.isEmpty(adminList.get("list"))) {
            return Result.result(InfoCode.QUERY_EMPTY, InfoCode.MESSAGE_QUERY_EMPTY, null, System.currentTimeMillis());
        }
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, adminList, System.currentTimeMillis());

    }

    @PostMapping("/createAdmin")
    public Result createAdmin(@RequestBody DtsAdmin admin) {
        System.out.println("createAdmin******:"+admin);
        int i = dtsAdminService.AdminUsernameCount(admin.getUserName());

        if (i > 0) {
            return Result.result(InfoCode.FAILED, "用户名已存在", null, System.currentTimeMillis());
        } else {
            String rawPassword = admin.getPassword();
            String md5Pwd = MD5Util.string2MD5(rawPassword);
            admin.setPassword(md5Pwd);
            dtsAdminService.createAdmin(admin);
        }
        return Result.result(InfoCode.CREATED, InfoCode.MESSAGE_CREATED, null, System.currentTimeMillis());
    }
    @PostMapping("/updateAdmin")
    public Result updateAdmin(@RequestBody DtsAdmin admin){
//        int i = dtsAdminService.AdminUsernameCount(admin.getUserName())
            String rawPassword = admin.getPassword();
            String md5Pwd = MD5Util.string2MD5(rawPassword);
            admin.setPassword(md5Pwd);
            dtsAdminService.changeAdminInfoById(admin);

        return Result.result(InfoCode.OK, "", null, System.currentTimeMillis());
    }
    @PostMapping("/deleteAdmin")
    public Result deleteAdmin(@RequestBody DtsAdmin admin){
        if (admin.getId()!=null&&!admin.equals("0")){
            int i = dtsAdminService.deleteAdmin(admin);
            if (i>0){
                return Result.result(InfoCode.NO_CONTENT, InfoCode.MESSAGE_NO_CONTENT, null, System.currentTimeMillis());
            }else {
                return Result.result(InfoCode.FAILED, "删除失败", null, System.currentTimeMillis());
            }

        }
        return Result.result(InfoCode.NOT_FOUND,InfoCode.MESSAGE_NOT_FOUND, null, System.currentTimeMillis());
    }
}
